package net.suncaper.mvc.mapper.impl;

import net.suncaper.mvc.mapper.ReviewReplyMapper;
import net.suncaper.mvc.model.domain.ReviewReply;
import net.suncaper.mvc.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * ReviewReply表数据库访问接口实现类
 */
public class ReviewReplyMapperImpl implements ReviewReplyMapper {
    private static final QueryRunner RUNNER = new QueryRunner();

    /**
     * 添加评论回复
     * @param reviewReply 评论回复信息
     * @return 添加结果
     */
    @Override
    public boolean insertReviewReply(ReviewReply reviewReply) {
        String sql = "INSERT INTO review_reply(review_id, user_id, reply_time, content) VALUES (?, ?, ?, ?)";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    reviewReply.getReviewId(), reviewReply.getUserId(),
                    reviewReply.getReplyTime(), reviewReply.getContent()
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 根据回复ID获取评论回复
     * @param replyId 回复ID
     * @return 评论回复信息
     */
    @Override
    public ReviewReply selectReviewReplyById(Long replyId) {
        String sql = "SELECT * FROM review_reply WHERE reply_id = ?";
        Connection connection = JDBCUtils.getConnection();
        ReviewReply reviewReply = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            pstmt = connection.prepareStatement(sql);
            pstmt.setLong(1, replyId);
            rs = pstmt.executeQuery();
            
            if (rs.next()) {
                reviewReply = new ReviewReply();
                reviewReply.setReplyId(rs.getLong("reply_id"));
                reviewReply.setReviewId(rs.getLong("review_id"));
                reviewReply.setUserId(rs.getString("user_id"));
                reviewReply.setReplyTime(rs.getTimestamp("reply_time"));
                reviewReply.setContent(rs.getString("content"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeResources(rs, pstmt);
            JDBCUtils.close();
        }
        return reviewReply;
    }

    /**
     * 根据评论ID获取所有回复列表
     * @param reviewId 评论ID
     * @return 评论回复列表
     */
    @Override
    public List<ReviewReply> selectReviewRepliesByReviewId(Long reviewId) {
        String sql = "SELECT * FROM review_reply WHERE review_id = ? ORDER BY reply_time ASC";
        Connection connection = JDBCUtils.getConnection();
        List<ReviewReply> reviewReplies = new ArrayList<>();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            pstmt = connection.prepareStatement(sql);
            pstmt.setLong(1, reviewId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                ReviewReply reviewReply = new ReviewReply();
                reviewReply.setReplyId(rs.getLong("reply_id"));
                reviewReply.setReviewId(rs.getLong("review_id"));
                reviewReply.setUserId(rs.getString("user_id"));
                reviewReply.setReplyTime(rs.getTimestamp("reply_time"));
                reviewReply.setContent(rs.getString("content"));
                reviewReplies.add(reviewReply);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeResources(rs, pstmt);
            JDBCUtils.close();
        }
        return reviewReplies;
    }

    /**
     * 根据用户ID获取所有回复列表
     * @param userId 用户ID
     * @return 评论回复列表
     */
    @Override
    public List<ReviewReply> selectReviewRepliesByUserId(String userId) {
        String sql = "SELECT * FROM review_reply WHERE user_id = ? ORDER BY reply_time DESC";
        Connection connection = JDBCUtils.getConnection();
        List<ReviewReply> reviewReplies = new ArrayList<>();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, userId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                ReviewReply reviewReply = new ReviewReply();
                reviewReply.setReplyId(rs.getLong("reply_id"));
                reviewReply.setReviewId(rs.getLong("review_id"));
                reviewReply.setUserId(rs.getString("user_id"));
                reviewReply.setReplyTime(rs.getTimestamp("reply_time"));
                reviewReply.setContent(rs.getString("content"));
                reviewReplies.add(reviewReply);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeResources(rs, pstmt);
            JDBCUtils.close();
        }
        return reviewReplies;
    }

    /**
     * 查询所有评论回复
     * @return 评论回复列表
     */
    @Override
    public List<ReviewReply> selectAllReviewReplies() {
        String sql = "SELECT * FROM review_reply ORDER BY reply_time DESC";
        Connection connection = JDBCUtils.getConnection();
        List<ReviewReply> reviewReplies = new ArrayList<>();
        
        try {
            reviewReplies = RUNNER.query(
                    connection,
                    sql,
                    new BeanListHandler<>(ReviewReply.class)
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return reviewReplies;
    }

    /**
     * 更新评论回复
     * @param reviewReply 评论回复信息
     * @return 更新结果
     */
    @Override
    public boolean updateReviewReply(ReviewReply reviewReply) {
        String sql = "UPDATE review_reply SET content = ?, reply_time = ? WHERE reply_id = ?";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    reviewReply.getContent(),
                    reviewReply.getReplyTime(),
                    reviewReply.getReplyId()
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 通过回复ID删除评论回复
     * @param replyId 回复ID
     * @return 删除结果
     */
    @Override
    public boolean deleteReviewReplyById(Long replyId) {
        String sql = "DELETE FROM review_reply WHERE reply_id = ?";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    replyId
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }

    /**
     * 通过评论ID删除所有相关回复
     * @param reviewId 评论ID
     * @return 删除结果
     */
    @Override
    public boolean deleteReviewRepliesByReviewId(Long reviewId) {
        String sql = "DELETE FROM review_reply WHERE review_id = ?";
        Connection connection = JDBCUtils.getConnection();
        int rows = 0;
        try {
            rows = RUNNER.update(
                    connection,
                    sql,
                    reviewId
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.close();
        }
        return rows > 0;
    }
    
    /**
     * 关闭资源
     * @param rs ResultSet
     * @param stmt PreparedStatement
     */
    private void closeResources(ResultSet rs, PreparedStatement stmt) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
} 